package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.CaidandetailAdapter;
import com.keyinong.caizhengting.entity.CaidanEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：DingdandetailActivity.java
 * @功能: 订单详情
 */

public class DingdandetailActivity extends Activity {

    View iscatview = null;
    /**
     * 获得数据
     */
    ArrayList<CaidanEntity> infolist;
    HttpTools httptools = null;
    /**
     * 订单详情适配器
     */
    private CaidandetailAdapter caidanAdapter;
    /**
     * 菜单列表
     */
    private ListView lv;
    /**
     * 返回
     */
    private ImageButton ib_fanhui;
    /**
     * 取单
     */
    private Button btn_qudan;
    /**
     * 订单号
     */
    private TextView tv_dingdanhao;
    private TextView tv_orderstate;
    /**
     * 订单状态
     */
    private String state;
    private String id;
    private String total;
    /**
     * 合计
     */
    private TextView tv_fee;
    /**
     * 取餐编号
     */
    private TextView tv_bianhao;
    /**
     * 取餐时间
     */
    private TextView tv_qucanshijian;
    /***/
    /**
     * 领餐时间
     */
    private TextView tv_time;
    private RelativeLayout rl_lingcanshijian;
    private String token;
    private String orderid;
    private String note;

    private RelativeLayout mRlGetGoodsTime;

    private int mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        Intent intent = getIntent();
        if (null != intent) {
            mType = intent.getIntExtra("type", 0);
        }

        Caidan();
    }

    private void initRes() {
        setContentView(R.layout.activity_dingdandetail);

        lv = (ListView) findViewById(R.id.lv_caidan);
//		tv_heji=(TextView)findViewById(R.id.textView10);
        tv_dingdanhao = (TextView) findViewById(R.id.tv_dingdanhao);
        tv_fee = (TextView) findViewById(R.id.tv_fee);
        tv_bianhao = (TextView) findViewById(R.id.tv_bianhao);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_qucanshijian = (TextView) findViewById(R.id.tv_qucanshijian);
        rl_lingcanshijian = (RelativeLayout) findViewById(R.id.rl_lingcanshijian);
        ib_fanhui = (ImageButton) findViewById(R.id.ib_back);
        tv_orderstate = (TextView) findViewById(R.id.tv_orderstate);
        mRlGetGoodsTime = (RelativeLayout) findViewById(R.id.rl_qucanshijian);
        ib_fanhui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
                //Intent intent = new Intent();
                //intent.setClass(getApplicationContext(), FanqiedingcanActivity.class);
                //startActivity(intent);
            }
        });
        btn_qudan = (Button) findViewById(R.id.btn);
        btn_qudan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (state.equals("0")) {
//					tv_orderstate.setText("待支付");
//					btn_qudan.setVisibility(View.VISIBLE);
//					btn_qudan.setText("立即支付");
//					intent.putExtra("orderid", id);
//					intent.putExtra("price", total);
//					intent.setClass(getApplicationContext(), PayDemoActivity.class);
//					startActivity(intent);
                    paydialog();
                } else if (state.equals("1")) {
                    intent.setClass(getApplicationContext(), ErweimaActivity.class);
                    intent.putExtra("id", id);
                    startActivity(intent);
                }

            }
        });

        if (mType != 0) {
            mRlGetGoodsTime.setVisibility(View.GONE);
        }
    }

    /**
     * 获取订单详情
     */
    private void Caidan() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        infolist = new ArrayList<CaidanEntity>();
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        String orderid = getIntent().getStringExtra("orderid");
        //		Log.i("info","orderid---" +orderid);
        if (httptools == null) {
            httptools = new HttpTools(getApplicationContext());
        }
        httptools.orderdetail(token, orderid, new JsonCaidan());

    }

    /**
     * 支付弹窗
     */
    private void paydialog() {

        final Dialog dialog = new Dialog(DingdandetailActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        iscatview = LayoutInflater.from(DingdandetailActivity.this).inflate(
                R.layout.dialog_pay, null);
        TextView tital = (TextView) iscatview.findViewById(R.id.tital);
        TextView tv_no = (TextView) iscatview.findViewById(R.id.tv_no);
        TextView tv_yes = (TextView) iscatview.findViewById(R.id.tv_yes);
        tital.setText("是否立即支付？");
        dialog.setContentView(iscatview);
        dialog.show();
        tv_no.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.putExtra("price", total);
//				intent.putExtra("orderid", id);
//				intent.setClass(DingdandetailActivity.this, BalancepayActivity.class);
//				startActivity(intent);
                dialog.dismiss();
            }
        });
        tv_yes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Log.e("lh", "iscat-----"+iscat);
//				CallPhone.phone(LineDetailActivity.this, phone);
//				Intent intent = new Intent();
//				intent.putExtra("price", total);
//				intent.putExtra("orderid", id);
//				intent.setClass(DingdandetailActivity.this, PayDemoActivity.class);
//				startActivity(intent);
                Balancepay();
                dialog.dismiss();
            }
        });
    }

    /**
     * 余额支付
     */
    private void Balancepay() {
        SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        //		Log.i("zq", "balancepayorderid---"+orderid);
        if (httptools == null) {
            httptools = new HttpTools(getApplicationContext());
        }
//		httptools.submitpay(token,id,new JsonHttpResponseHandler() {
//
//			@Override
//			public void onSuccess(int statusCode, Header[] headers,
//					JSONObject response) {
//				super.onSuccess(statusCode, headers, response);
//				try {
//					boolean code = response.getBoolean("code");
//					String msg = response.getString("msg");
////					Log.i("zq", "balancepay---"+response.toString());
//					if (code == true) {
//						//						String data=response.getString("data");
//						Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
////						Intent intent = new Intent();
////						intent.setClass(getApplicationContext(), FanqiedingcanActivity.class);
////						startActivity(intent);
//						finish();
//					} else {
////						flag=false;
//						Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
////						finish();
//					}
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//
//		});
    }

    public class JsonCaidan extends JsonHttpResponseHandler {

        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(DingdandetailActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            MyShowDialog.closeLoadingDialog();
            initRes();
            super.onSuccess(statusCode, headers, response);
            try {
                Log.i("zq", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    Log.i("zq", "订单详情---" + response.toString());
                    JSONObject object = response.getJSONObject("data");
                    id = object.getString("id");
//					String order_time = object.getString("order_time");
                    String take_time = object.getString("take_time");
                    String book_time = object.getString("book_time");
                    String dayno = object.getString("dayno");
//					String paymodeid = object.getString("paymodeid");
                    total = object.getString("total");
                    state = object.getString("state");
//					String fee = object.getString("fee");
//					String recmode = object.getString("recmode");
                    String orderno = object.getString("orderno");
                    state = object.getString("state");
//					String note = object.getString("note");
//					String refund = object.getString("refund");
//					String more = object.getString("more");
//					String off = object.getString("off");
                    JSONArray array = object.getJSONArray("details");
                    for (int j = 0; j < array.length(); j++) {
                        JSONObject details = array.getJSONObject(j);
                        String name = details.getString("name");
                        String amount = details.getString("amount");
                        String price = details.getString("price");
//						String sname = details.getString("sname");
                        infolist.add(new CaidanEntity(amount, name, price, ""));
                    }
                    SharedPreferences spuser = getSharedPreferences("id",
                            Context.MODE_PRIVATE);
                    Editor editorid = spuser.edit();
                    editorid.putString("id", id);
                    editorid.commit();
                    if (state.equals("-1")) {
                        btn_qudan.setVisibility(View.VISIBLE);
                        rl_lingcanshijian.setVisibility(View.GONE);
                        btn_qudan.setText("已取消");
                        tv_orderstate.setText("已取消");
                    } else if (state.equals("0")) {
                        btn_qudan.setVisibility(View.VISIBLE);
                        btn_qudan.setText("立即支付");
                        rl_lingcanshijian.setVisibility(View.GONE);
//						intent.putExtra("orderid", id);
//						intent.putExtra("price", total);
//						intent.setClass(getApplicationContext(), PayDemoActivity.class);
//						startActivity(intent);
//						paydialog();
                        tv_orderstate.setText("待支付");
                    } else if (state.equals("1")) {
                        if (mType == 0) {
                            tv_orderstate.setText("待取餐");
                            btn_qudan.setText("领取取餐二维码");
                        } else {
                            tv_orderstate.setText("待取货");
                            btn_qudan.setText("领取取货二维码");
                        }
                        btn_qudan.setVisibility(View.VISIBLE);

                        rl_lingcanshijian.setVisibility(View.GONE);

                    } else if (state.equals("2")) {
                        btn_qudan.setVisibility(View.VISIBLE);
                        btn_qudan.setText("已完成");
                        rl_lingcanshijian.setVisibility(View.VISIBLE);
                        tv_orderstate.setText("已完成");
                    }
                    tv_bianhao.setText(dayno);
                    tv_qucanshijian.setText(book_time);
                    tv_time.setText(take_time);
//					tv_heji.setText(total);
//					tv_fee.setText(""+(int)(Double.parseDouble(total)*10));
                    tv_fee.setText(total);
                    tv_dingdanhao.setText(orderno);
                    caidanAdapter = new CaidandetailAdapter(getApplicationContext(), infolist);
                    lv.setAdapter(caidanAdapter);
                    lv.setDivider(null);
//					Utility.setListViewHeightBasedOnChildren(lv);
                } else {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
